const Router = require("@koa/router");
const router = new Router();
const Op = require("sequelize").Op;
//导入AreaModel
const { areaModel } = require("../database/index");

router.post("/addArea", async (ctx, next) => {
  console.log(ctx.request.body);
  const jane = await areaModel.create(ctx.request.body);
  if (jane != "" || null) {
    ctx.body = {
      code: 200,
      msg: "success",
      data: {
        message: "Area success",
        datas: jane,
      },
    };
  } else {
    ctx.body = {
      code: 200,
      msg: "error",
      data: {
        message: "Area failed",
        datas: jane,
      },
    };
  }
});

router.delete("/:id", async (ctx, next) => {
  let AreaId = ctx.request.params.id;
  const result = await areaModel.destroy({
    where: {
      AreaId,
    },
  });
  if (result) {
    ctx.body = {
      code: 200,
      msg: "success",
    };
  } else {
    ctx.body = {
      code: 200,
      msg: "error",
      data: {
        message: "delete Area failed",
      },
    };
  }
});

router.post("/:id", async (ctx, next) => {
  let AreaId = ctx.request.params.id;
  const whereOption = {};
  if (AreaId) {
    whereOption.AreaId = AreaId;
  }
  let obj = ctx.request.body;
  console.log(obj);
  const result = await areaModel.update(obj, {
    where: whereOption,
  });
  if (result) {
    ctx.body = {
      code: 200,
      msg: "success",
    };
  } else {
    ctx.body = {
      code: 200,
      msg: "error",
      data: {
        message: "delete Area failed",
      },
    };
  }
});

router.get("/getAllArea", async function (ctx, next) {
  const pageSize = ctx.query.pageSize;
  const pageNo = ctx.query.pageNo;
  const name = ctx.query.name;
  let whereOption = {};
  console.log(name);
  if (name) {
    whereOption.AreaName = {
      [Op.like]: `%${name}%`,
    };
  }

  let result = await areaModel.findAll({
    limit: Number(pageSize),
    offset: (pageNo - 1) * pageSize,
    where: whereOption,
  });
  console.log(result)
  let total = await areaModel.findAll({
    where: whereOption,
  });
  if (result) {
    ctx.body = {
      code: 200,
      msg: "success",
      data: result,
      total: total.length,
    };
  } else {
    ctx.body = {
      code: 200,
      msg: "error",
      data: {
        message: "Area failed",
      },
    };
  }
});

module.exports = router;
